import { formatTime } from '@gnlab/utils'
import { Table, message } from 'antd'
import type { ColumnProps } from 'antd/lib/table'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import type { ArticleData } from '@/services/features/new-rank'
import './articles.module.less'

export function Articles({
  contactId,
  open,
  onClose,
}: {
  contactId: string
  open: boolean
  onClose: () => void
}) {
  return <EditModal open={open} title="详细数据" width={800} onCancel={onClose}>
    {open ? <Content contactId={contactId} /> : null}
  </EditModal>
}

function Content({ contactId }: { contactId: string }) {
  const [articles, setArticles] = useState<ArticleData[]>([])
  const [loading, setLoading] = useState(true)
  useEffect(() => {
    void services.features.newRank.getArticles(contactId).then(res => {
      setLoading(false)
      if (res.success) setArticles(res.data)
      else void message.warning('获取文章数据失败：' + res.error)
    })
  }, [contactId])

  const columns: ColumnProps<ArticleData>[] = useMemo(
    () => [
      {
        title: '文章标题',
        render(data: ArticleData) {
          return <a href={data.url} target="_blank" rel="noreferrer">
            {data.title}
          </a>
        },
      },
      {
        title: '阅读量',
        dataIndex: 'readNum',
        width: 90,
        align: 'center',
        sorter: sorter.bind(null, 'readNum'),
      },
      {
        title: '在看量',
        dataIndex: 'likeNum',
        width: 90,
        align: 'center',
        sorter: sorter.bind(null, 'likeNum'),
      },
      {
        title: '点赞量',
        dataIndex: 'preLikeNum',
        width: 90,
        align: 'center',
        sorter: sorter.bind(null, 'preLikeNum'),
      },
      {
        title: '评论量',
        dataIndex: 'commentNum',
        width: 90,
        align: 'center',
        sorter: sorter.bind(null, 'commentNum'),
        defaultSortOrder: 'descend',
      },
      {
        title: '发布时间',
        width: 120,
        align: 'center',
        render(data: ArticleData) {
          return formatTime(data.publicTime)
        },
        sorter(a, b) {
          return a.publicTime.getTime() - b.publicTime.getTime()
        },
      },
    ],
    [],
  )

  return <main>
    <Table
      loading={loading}
      dataSource={articles}
      columns={columns}
      sortDirections={['descend', 'ascend']}
      rowKey="url"
    />
  </main>
}

function sorter(key: keyof ArticleData, a: ArticleData, b: ArticleData) {
  return (a[key] as number) - (b[key] as number)
}
